package com.seanchenxi.gwt.xmlrpc.client.model.impl;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.seanchenxi.gwt.xmlrpc.client.ResponseHandler;
import com.seanchenxi.gwt.xmlrpc.client.model.BaseModel;
import com.seanchenxi.gwt.xmlrpc.client.util.XmlRpcParser;

public class BaseModelListResponseHandler<T extends BaseModel> implements ResponseHandler<ArrayList<T>>{

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<T> handleResponse(String responseText) {
		ArrayList<T> models = null;
		try {
			if(responseText != null && responseText.length() > 0){
				GWT.log(responseText);
				Object list = XmlRpcParser.parserResponse(responseText);
				if(list instanceof ArrayList<?>){
					models = new ArrayList<T>();
					for(Object object : (ArrayList<?>)list){
						if(object instanceof HashMap<?,?>){
							BaseModel model = new BaseModelImpl((HashMap<String, Object>)object);
							if(!models.contains(model)) models.add((T)model);
						}
					}
				}
			}
			return models;
		} catch (Throwable e) {
			GWT.log("Base Model Response Handler Error", e);
			return null;
		}
	}
}
